package cn.lecosa.spark.hbase;

import java.io.IOException;

import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTableInterface;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;

public class HbaseUtil {
  
	
	//禁用表
	public void disableTable(HBaseAdmin admin, String table)  {
		try {
			admin.disableTable(table);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
  
	
	//删除表
	public void dropTable(HBaseAdmin admin, String tableName)
			{
		if (existsTable(admin, tableName)) {
			disableTable(admin, tableName);
			try {
				admin.deleteTable(tableName);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
  
	
	//判定表是否存在
	public static boolean existsTable(HBaseAdmin admin, String tableName) {
		try {
			return admin.tableExists(tableName.getBytes());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}

	// 创建数据库
	public static void createTable(Admin admin, String tableName, String cf) {
		HTableDescriptor hd = new HTableDescriptor(tableName);
		HColumnDescriptor hc = new HColumnDescriptor(cf);
	//	hc.setMaxVersions(10);
		hd.addFamily(hc);
		try {
			admin.createTable(hd);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static Result getValues(HTableInterface htable, String rowkey,String cf) {
		Result result = null;
		Get get = new Get(rowkey.getBytes());
		get.addFamily(cf.getBytes());
		try {
			result = htable.get(get);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	// 插入hbase中获得数据，傳入表名tableName,行键rowkey,列族cf,列名column,得到值value.
	public static String getValue(HTableInterface htable, 
			String rowkey, String cf, String column) {
		Get get = new Get(rowkey.getBytes());
		get.addColumn(cf.getBytes(), column.getBytes());
		String createTime = null;
		try {
			Result result = htable.get(get);
			if (result.value() != null) {
				createTime = new String(result.value());
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return createTime;
	}

	// 插入數據到Hbase中，傳入表名tableName,行键rowkey,列族cf,列名column,值value.
	public static void putToHBase(HTableInterface htable, 
			String rowkey, String cf, String column, String value) {

		Put put = new Put(rowkey.getBytes());
		put.add(cf.getBytes(), column.getBytes(), value.getBytes());
		try {
			htable.put(put);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
